package com.resys.server.controller;
import com.resys.entity.dto.LogDto;
import com.resys.entity.dto.TokenCustomerDto;
import com.resys.entity.dto.TokenUserInfoDto;
import com.resys.entity.enums.ResponseCodeEnum;
import com.resys.entity.po.Roomstatuslog;
import com.resys.entity.po.User;
import com.resys.entity.vo.ResponseVO;
import com.resys.exception.BusinessException;
import com.resys.server.component.RedisComponent;
import com.resys.service.RoomstatuslogService;
import com.resys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class ABaseController {
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private UserService userService;
    @Resource
    private RoomstatuslogService roomstatuslogService;
    protected static final String STATUC_SUCCESS = "success";

    protected static final String STATUC_ERROR = "error";

    protected <T> ResponseVO getSuccessResponseVO(T t) {
        ResponseVO<T> responseVO = new ResponseVO<>();
        responseVO.setStatus(STATUC_SUCCESS);
        responseVO.setCode(ResponseCodeEnum.CODE_200.getCode());
        responseVO.setInfo(ResponseCodeEnum.CODE_200.getMsg());
        responseVO.setData(t);
        return responseVO;
    }

    protected <T> ResponseVO getBusinessErrorResponseVO(BusinessException e, T t) {
        ResponseVO vo = new ResponseVO();
        vo.setStatus(STATUC_ERROR);
        if (e.getCode() == null) {
            vo.setCode(ResponseCodeEnum.CODE_600.getCode());
        } else {
            vo.setCode(e.getCode());
        }
        vo.setInfo(e.getMessage());
        vo.setData(t);
        return vo;
    }

    protected <T> ResponseVO getServerErrorResponseVO(T t) {
        ResponseVO vo = new ResponseVO();
        vo.setStatus(STATUC_ERROR);
        vo.setCode(ResponseCodeEnum.CODE_500.getCode());
        vo.setInfo(ResponseCodeEnum.CODE_500.getMsg());
        vo.setData(t);
        return vo;
    }
    public void saveToken2Cookie(HttpServletResponse response, String token,String role){
        Cookie cookie = new Cookie("token"+role,token);
        cookie.setMaxAge(60*60*24*7);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);

    }
    public TokenUserInfoDto getTokenUserInfo(String role){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if(request == null){
           return null;
        }
        //String token = request.getHeader("token"+role);
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            log.error("No cookies found");
            return null; // 或者抛出自定义异常
        }
        String token = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token" + role)) {
                token = cookie.getValue();
                break;
            }
        }
        if (token == null) {
            log.error("Token cookie is null for role: " + role);
            return null; // 或者抛出自定义异常
        }
        log.info("token"+role+"="+token);
        return redisComponent.getTokenInfo(token,role);

    }
    public TokenCustomerDto getTokenCustomer(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if(request == null){
            return null;
        }
        //String token = request.getHeader("token"+role);
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            log.error("No cookies found");
            return null; // 或者抛出自定义异常
        }
        String token = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token" + "customer")) {
                token = cookie.getValue();
                break;
            }
        }
        if (token == null) {

            return null; // 或者抛出自定义异常
        }
        log.info("tokencustomer"+"="+token);
        return redisComponent.getTokenInfo4Cilent(token);
    }
    public void cleanCookie(HttpServletResponse response,String role) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie[] cookies = request.getCookies();
        String token = null;

        if (cookies == null) {
            return;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token"+role)) {
                redisComponent.deleteToken(cookie.getValue(),role);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
                break;
            }
        }
    }
    public boolean checkSameName(String name ,String checkname){
        User user = userService.getUserByUsername(checkname);
        if(user != null ){
            return false;
        }
        return true;
    }
    public  void saveCilentToken2Cookie(HttpServletResponse response,String token){
        Cookie cookie = new Cookie("token"+"customer",token);
        cookie.setMaxAge(60*60*24*7);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }
    protected String getIpAddr() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    public void cleanTokenCilent(){
        redisComponent.deleteCilentToken();
    }
    public void writelog(LogDto logDto){
        roomstatuslogService.write(logDto);
    }
}
